<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="业务id" prop="bussniessId">
        <el-input
          v-model="queryParams.bussniessId"
          placeholder="请输入业务id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="task编号" prop="taskId">
        <el-input
          v-model="queryParams.taskId"
          placeholder="请输入task编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作人" prop="assignee">
        <el-input
          v-model="queryParams.assignee"
          placeholder="请输入操作人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作人id" prop="assigneeId">
        <el-input
          v-model="queryParams.assigneeId"
          placeholder="请输入操作人id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="applicationTime">
        <el-date-picker clearable
          v-model="queryParams.applicationTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="申请人" prop="applicat">
        <el-input
          v-model="queryParams.applicat"
          placeholder="请输入申请人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人id" prop="applicatId">
        <el-input
          v-model="queryParams.applicatId"
          placeholder="请输入申请人id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="完成时间" prop="finishTime">
        <el-date-picker clearable
          v-model="queryParams.finishTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择完成时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否处理完成" prop="isHandle">
        <el-input
          v-model="queryParams.isHandle"
          placeholder="请输入是否处理完成"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核步骤" prop="stepNo">
        <el-input
          v-model="queryParams.stepNo"
          placeholder="请输入审核步骤"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:tasks:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:tasks:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:tasks:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:tasks:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tasksList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="业务id" align="center" prop="bussniessId" />
      <el-table-column label="task编号" align="center" prop="taskId" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="类型" align="center" prop="type" />
      <el-table-column label="操作人" align="center" prop="assignee" />
      <el-table-column label="操作人id" align="center" prop="assigneeId" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="申请时间" align="center" prop="applicationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applicationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="applicat" />
      <el-table-column label="申请人id" align="center" prop="applicatId" />
      <el-table-column label="完成时间" align="center" prop="finishTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否处理完成" align="center" prop="isHandle" />
      <el-table-column label="审核步骤" align="center" prop="stepNo" />
      <el-table-column label="额外字段1" align="center" prop="extraField1" />
      <el-table-column label="额外字段2" align="center" prop="extraField2" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            link 
            :type="getProcessButtonType(scope.row)" 
            :disabled="isProcessButtonDisabled(scope.row)"
            icon="Edit" 
            @click="handleHandle(scope.row)"
          >
            处理
          </el-button>
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:tasks:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:tasks:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改待办任务对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="tasksRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="业务id" prop="bussniessId">
          <el-input v-model="form.bussniessId" placeholder="请输入业务id" />
        </el-form-item>
        <el-form-item label="task编号" prop="taskId">
          <el-input v-model="form.taskId" placeholder="请输入task编号" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="操作人" prop="assignee">
          <el-input v-model="form.assignee" placeholder="请输入操作人" />
        </el-form-item>
        <el-form-item label="操作人id" prop="assigneeId">
          <el-input v-model="form.assigneeId" placeholder="请输入操作人id" />
        </el-form-item>
        <el-form-item label="申请时间" prop="applicationTime">
          <el-date-picker clearable
            v-model="form.applicationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择申请时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请人" prop="applicat">
          <el-input v-model="form.applicat" placeholder="请输入申请人" />
        </el-form-item>
        <el-form-item label="申请人id" prop="applicatId">
          <el-input v-model="form.applicatId" placeholder="请输入申请人id" />
        </el-form-item>
        <el-form-item label="完成时间" prop="finishTime">
          <el-date-picker clearable
            v-model="form.finishTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否处理完成" prop="isHandle">
          <el-input v-model="form.isHandle" placeholder="请输入是否处理完成" />
        </el-form-item>
        <el-form-item label="审核步骤" prop="stepNo">
          <el-input v-model="form.stepNo" placeholder="请输入审核步骤" />
        </el-form-item>
        <el-form-item label="额外字段1" prop="extraField1">
          <el-input v-model="form.extraField1" placeholder="请输入额外字段1" />
        </el-form-item>
        <el-form-item label="额外字段2" prop="extraField2">
          <el-input v-model="form.extraField2" placeholder="请输入额外字段2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tasks">
import { listTasks, getTasks, delTasks, addTasks, updateTasks } from "@/api/system/tasks"
import useUserStore from '@/store/modules/user'
import { useRouter } from 'vue-router'
import { onActivated } from 'vue'

const router = useRouter()
const userStore = useUserStore()
const { proxy } = getCurrentInstance()

// ✅ 权限控制：检查当前用户是否有权限查看退住申请相关的待办任务
const canViewCheckoutTasks = computed(() => {
  const currentUser = userStore.name
  console.log('当前用户:', currentUser)
  
  // 只有退住审批员a (tuizhushenpiyuana) 才能查看退住申请相关的待办任务
  if (currentUser === 'tuizhushenpiyuana') {
    console.log('✅ 退住审批员a，允许查看退住申请相关的待办任务')
    return true
  }
  
  console.log('❌ 非退住审批员a，不能查看退住申请相关的待办任务')
  return false
})

const tasksList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    bussniessId: null,
    taskId: null,
    title: null,
    type: null,
    assignee: null,
    assigneeId: null,
    status: 1, // 🔥 只查询待处理的任务
    applicationTime: null,
    applicat: null,
    applicatId: null,
    finishTime: null,
    isHandle: null, // 🔥 修改：不限制处理状态，显示所有任务（包括已完成的退住任务）
    stepNo: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询待办任务列表 */
function getList() {
  loading.value = true
  listTasks(queryParams.value).then(response => {
    tasksList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    bussniessId: null,
    taskId: null,
    title: null,
    type: null,
    assignee: null,
    assigneeId: null,
    status: null,
    applicationTime: null,
    applicat: null,
    applicatId: null,
    finishTime: null,
    isHandle: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    stepNo: null,
    extraField1: null,
    extraField2: null
  }
  proxy.resetForm("tasksRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  // 🔥 重置时保持isHandle为null，不限制处理状态
  queryParams.value.isHandle = null
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加待办任务"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getTasks(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改待办任务"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["tasksRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateTasks(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addTasks(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除待办任务编号为"' + _ids + '"的数据项？').then(function() {
    return delTasks(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/tasks/export', {
    ...queryParams.value
  }, `tasks_${new Date().getTime()}.xlsx`)
}

// 判断处理按钮是否应该被禁用
function isProcessButtonDisabled(row) {
  // 只针对退住申请类型（type = 1）且完成状态为1的任务禁用按钮
  if (row.type === 1 && row.isHandle === 1) {
    console.log('退住申请任务已完成，禁用处理按钮:', {
      id: row.id,
      title: row.title,
      type: row.type,
      isHandle: row.isHandle
    })
    return true
  }
  return false
}

// 获取处理按钮的类型
function getProcessButtonType(row) {
  // 如果按钮被禁用，返回info类型（灰色）
  if (isProcessButtonDisabled(row)) {
    return 'info'
  }
  // 否则返回primary类型（蓝色）
  return 'primary'
}

/** 处理按钮操作 */
function handleHandle(row) {
  console.log('=== 开始处理任务 ===')
  console.log('完整任务数据:', row)
  console.log('任务ID:', row.id)
  console.log('任务标题:', row.title)
  console.log('任务类型:', row.type)
  console.log('业务ID:', row.bussniessId)
  console.log('步骤号:', row.stepNo)
  console.log('操作人:', row.assignee)
  console.log('申请人:', row.applicat)
  console.log('申请时间:', row.applicationTime)
  console.log('状态:', row.status)
  
  // 根据任务类型跳转到不同的审批页面
  if (row.type === 1) {
    console.log('=== 处理退住申请 ===')
    // 退住申请 - 根据步骤跳转到不同页面
    const step = row.stepNo || 2 // 默认第二步（申请审批）
    console.log('退住申请步骤:', step)
    
    // 准备传递的数据
    const taskData = {
      id: row.bussniessId,
      taskId: row.taskId,
      ptId: row.id,
      step: step,
      type: row.type,
      title: row.title,
      assignee: row.assignee,
      assigneeId: row.assigneeId,
      applicationTime: row.applicationTime,
      applicant: row.applicat,
      applicantId: row.applicatId,
      status: row.status,
      isHandle: row.isHandle,
      stepNo: row.stepNo
    }
    
    console.log('准备传递的退住任务数据:', taskData)
    
    // 将任务数据保存到sessionStorage，供目标页面使用
    sessionStorage.setItem('checkout_task_data', JSON.stringify(taskData))
    console.log('已保存退住任务数据到sessionStorage')
    
    // 根据审核步骤跳转到不同页面
    if (step === 3) {
      console.log('步骤3：跳转到解除合同页面')
      router.push({
        path: '/splccs/jcht',
        query: {
          id: row.bussniessId, // 传递业务ID
          taskId: row.taskId,
          ptid: row.id,
          step: step,
          type: row.type
        }
      })
    } else if (step === 4) {
      console.log('步骤4：跳转到账单调整页面')
      router.push({
        path: '/splccs/zdtz',
        query: {
          id: row.bussniessId, // ✅ 传递业务ID
          taskId: row.taskId,
          ptid: row.id,
          step: step,
          type: row.type
        }
      })
    } else if (step === 5) {
      console.log('步骤5：跳转到账单审批页面')
      router.push({
        path: '/splccs/zdtzh',
        query: {
          id: row.bussniessId, // ✅ 传递业务ID
          taskId: row.taskId,
          ptid: row.id,
          step: step,
          type: row.type
        }
      })
    } else if (step === 6) {
      console.log('步骤6：跳转到副院长审批退住页面')
      router.push({
        path: '/splccs/fyzsptz',
        query: {
          id: row.bussniessId, // ✅ 传递业务ID
          taskId: row.taskId,
          ptid: row.id,
          step: step,
          type: row.type
        }
      })
    } else if (step === 7) {
      console.log('步骤7：跳转到账单调整后提款页面')
      router.push({
        path: '/splccs/zdtzhtk',
        query: {
          id: row.bussniessId, // ✅ 传递业务ID
          taskId: row.taskId,
          ptid: row.id,
          step: step,
          type: row.type
        }
      })
    } else {
      console.log('步骤' + step + '：跳转到审批申请页面')
      router.push({
        path: '/splccs/spsq',
        query: {
          id: row.bussniessId, // 使用业务ID
          taskId: row.taskId,
          ptid: row.id,
          step: step,
          type: row.type,
          mode: 'approval' // 审批模式
        }
      })
    }
  } else if (row.type === 3) {
    console.log('=== 处理入住申请 ===')
    // 入住申请 - 根据步骤号跳转到对应页面
    const step = row.stepNo || 1 // 默认第一步
    console.log('入住申请步骤:', step)
    
    router.push({
      path: '/system/management/checkInForm',
      query: {
        id: row.bussniessId,
        taskId: row.taskId,
        ptId: row.id,
        step: step, // 根据实际步骤号
        type: row.type,
        mode: 'approval' // 审批模式
      }
    })
  } else if (row.type === 2) {
    console.log('=== 处理type=2的任务 ===')
    console.log('任务标题:', row.title)
    console.log('任务类型:', row.type)
    console.log('步骤号:', row.stepNo)
    
    // 准备传递的数据
    const taskData = {
      id: row.bussniessId,
      taskId: row.taskId,
      ptId: row.id,
      step: row.stepNo || 2,
      type: row.type,
      title: row.title,
      assignee: row.assignee,
      assigneeId: row.assigneeId,
      applicationTime: row.applicationTime,
      applicant: row.applicat,
      applicantId: row.applicatId,
      status: row.status,
      isHandle: row.isHandle,
      stepNo: row.stepNo
    }
    
    console.log('准备传递的任务数据:', taskData)
    
    if (row.title && row.title.includes('退住申请')) {
      console.log('=== 识别为退住申请 ===')
      console.log('跳转到退住审批页面:', row.title, '步骤:', row.stepNo)
      
      // 将任务数据保存到sessionStorage，供目标页面使用
      sessionStorage.setItem('checkout_task_data', JSON.stringify(taskData))
      console.log('已保存退住任务数据到sessionStorage')
      
      const queryParams = {
        id: row.bussniessId,
        taskId: row.taskId,
        ptId: row.id,
        step: row.stepNo || 2,
        type: row.type,
        mode: 'approval' // 审批模式
      }
      console.log('跳转参数:', queryParams)
      
      router.push({
        path: '/splccs/spsq',
        query: queryParams
      })
    } else if (row.title && row.title.includes('请假申请')) {
      console.log('=== 识别为请假申请 ===')
      console.log('跳转到请假审批页面:', row.title, '步骤:', row.stepNo)
      
      // 将任务数据保存到sessionStorage，供目标页面使用
      sessionStorage.setItem('leave_task_data', JSON.stringify(taskData))
      console.log('已保存请假任务数据到sessionStorage')
      
      const queryParams = {
        id: row.bussniessId,
        taskId: row.taskId,
        ptId: row.id,
        step: row.stepNo || 2,
        type: row.type,
        mode: 'approval' // 审批模式
      }
      console.log('跳转参数:', queryParams)
      
      router.push({
        path: '/system/sq',
        query: queryParams
      })
    } else {
      console.log('=== 默认情况，跳转到请假审批页面 ===')
      console.log('任务标题:', row.title, '步骤:', row.stepNo)
      
      // 将任务数据保存到sessionStorage，供目标页面使用
      sessionStorage.setItem('leave_task_data', JSON.stringify(taskData))
      console.log('已保存默认任务数据到sessionStorage')
      
      const queryParams = {
        id: row.bussniessId,
        taskId: row.taskId,
        ptId: row.id,
        step: row.stepNo || 2,
        type: row.type,
        mode: 'approval' // 审批模式
      }
      console.log('跳转参数:', queryParams)
      
      router.push({
        path: '/system/sq',
        query: queryParams
      })
    }
  } else {
    console.log('=== 处理其他类型任务 ===')
    console.log('任务类型:', row.type)
    console.log('默认跳转到请假审批页面')
    
    router.push({
      path: '/system/sq',
      query: {
        id: row.bussniessId,
        taskId: row.taskId,
        ptId: row.id,
        step: 2,
        type: row.type
      }
    })
  }
  
  console.log('=== 任务处理完成 ===')
}

// 🔥 页面首次加载时获取任务列表
getList()

// 🔥【新增】页面被激活时（从其他页面返回）自动刷新任务列表
// 解决从处理页面返回后，列表数据不更新的问题
onActivated(() => {
  console.log('✅ 任务列表页面被激活，刷新数据...')
  getList()
})
</script>
